<script setup lang="ts">
// reactive 用来绑定复制的数据类型，比如数组、 对象等
import { reactive, readonly, shallowReactive } from "vue";
// let a = reactive("123123") Argument of type 'string' is not assignable to parameter of type 'object'.
let person = reactive({ name: "张三", age: 18 });
person.age = 20;

// reactive定义的数组或者对象，不能直接赋值修改，否则定义的数据userMenu将失去响应性。
let arr = reactive<number[]>([0, 0, 0]);
//  这样一步无法修改arr的值
console.log("改变之前arr", arr);

const changeArr1 = () => {
  setTimeout(() => {
    arr = [1, 2, 3];
    console.log("改变之后arr", arr);
  }, 1000);
};

//  解决方案一
const changeArr2 = () => {
  setTimeout(() => {
    const newArr = [4, 4, 4];
    arr.push(...newArr);
    console.log("第二次修改后arr", arr);
  }, 1000);
};

//  解决方案二  包裹一层对象
type Person = {
  list?: Array<number>;
};
let p1 = reactive<Person>({
  list: [],
});
const changeArr3 = () => {
  setTimeout(() => {
    const arrList = [1, 2, 3];
    p1.list = arrList;
    console.log("p1 ", p1);
  }, 1000);
};

// readonly 拷贝一份proxy对象将其设置为只读
// import { readonly } from "vue";
const p2 = reactive({ age: 11 });
const copyP2 = readonly(p2);
// copyP2.age++     Cannot assign to 'age' because it is a read-only property.
console.log("copyP2.age", copyP2);

// shallowReactive   只能对浅层的数据 如果是深层的数据只会改变值 不会改变视图
// import { shallowReactive } from "vue";
let myobj = reactive({
  a: 1,
  objb: {
    b: 2,
  },
});
let obj = shallowReactive(myobj);
console.log("改变前obj", obj);

const handleA = () => {
  obj.a = 2;
  console.log("改变后obj", obj);
};

const handleB = () => {
  obj.objb.b = 3;
  console.log(" 改变后obj", obj);
};
</script>
<template>
  <div>
    <div>reactive</div>
    <div>{{ arr }}====={{ p1 }}</div>
    <div>
      <button @click="changeArr1">修改arr1</button>
      <button @click="changeArr2">修改arr2</button>
      <button @click="changeArr3">修改arr3</button>
    </div>
    <div>{{ obj }}==={{ myobj }}</div>
    <div>
      <button @click="handleA">修改obj.a</button>
      <button @click="handleB">修改obj.b</button>
    </div>
  </div>
</template>